package com.wwf.controller;

import com.wwf.fegin.IAuthCodeService;
import com.wwf.pojo.UserInfo;
import com.wwf.pojo.UserToken;
import com.wwf.service.IUserService;
import com.wwf.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author wwf
 * @date 2021年02月04日 12:17:00
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @Autowired
    IAuthCodeService authCodeService;

    /**
     *
     * 检查邮箱是否注册过
     * @param email 邮箱
     * @return
     */
    @GetMapping("/isRegister/{email}")
    public Result<Map> isRegister(@PathVariable("email") String email){
        boolean register = userService.isRegister(email);
        Map<String,Boolean> resultMap = new HashMap<String,Boolean>();
        resultMap.put("isRegister",register);
        return new Result("200",resultMap);
    }

    @PostMapping("/register")
    public Result<Map> register(String email,String code,String password){
        Map<String,Object> resultMap = new HashMap<String,Object>();

        String state = authCodeService.validate(email, code);
        if("0".equals(state)){
            resultMap.put("state",2);
            resultMap.put("msg","验证码过期");
            return new Result("200",resultMap);

        }
        //resultMap.put("isRegister",register);
        UserInfo userInfo = new UserInfo();
        userInfo.setEmail(email);
        userInfo.setPassword(password);
        int id = userService.registerUser(userInfo);
        if(id >0){
            resultMap.put("state",1);
            resultMap.put("msg","注册成功");
        }else{
            resultMap.put("state",0);
            resultMap.put("msg","注册失败");
        }
        return new Result("200",resultMap);

    }

    /**
     *
     * 用户登录
     * @param email 邮箱
     * @param password 密码
     * @return
     */
    @PostMapping("login")
    public Result<Map> login(String email,String password){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        boolean b = userService.checkLogin(email, password);
        if(b){
            String accssToken = UUID.randomUUID().toString();
            userService.saveToken(email,accssToken);
            resultMap.put("accessToken", accssToken);
        }else{
            resultMap.put("accessToken","");
        }
        return new Result("200",resultMap);
    }

    /**
     *
     * 获取用户登录信息
     * @param accessToken 用户登录token
     * @return
     */
    @GetMapping("/info/{accessToken}")
    public Result<Map> info(@PathVariable("accessToken") String accessToken){
        Map<String,Object> resultMap = new HashMap<String,Object>();
        UserToken userToken = userService.findUserInfoBy(accessToken);
        resultMap.put("email",userToken.getEmail());
        return new Result("200",resultMap);
    }

}
